import path from 'node:path'

import { RequestMethod, ValidationPipe } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import type { NestExpressApplication } from '@nestjs/platform-express'

import { AppModule } from './app.module'
import { HttpExceptionFilter } from './filters/http-exception'
import { TransformInterceptor } from './interceptor/transform.interceptor'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['error', 'warn', 'log']
  })

  const option = new DocumentBuilder()
   .setTitle('Nestjs API')
   .setDescription('The Nestjs API description')
   .setVersion('1.0')
   .addBearerAuth()
   .build()

  const document = SwaggerModule.createDocument(app, option)
  SwaggerModule.setup('api-docs', app, document)

  app.setGlobalPrefix('api', {
    exclude: [
      { path: '/', method: RequestMethod.GET },
      { path: '/rank', method: RequestMethod.GET },
      { path: '/rank/list', method: RequestMethod.GET },
      { path: '/map', method: RequestMethod.GET },
      { path: '/map/area', method: RequestMethod.GET }
    ]
  })
  app.enableCors({
    origin: '*',
    exposedHeaders: ['Content-Disposition'],
    methods: ['PUT', 'POST', 'GET', 'DELETE', 'OPTIONS', 'HEAD'],
    allowedHeaders: [
      'Content-Type',
      'Content-Length',
      'Authorization',
      'Accept-Language',
      'Content-Language',
      'Accept',
      'X-Requested-With',
      'Origin',
      'Content-Disposition'
    ]
  })

  app.setBaseViewsDir(path.join(process.cwd(), './src/views'))
  app.setViewEngine('pug')

  app.useStaticAssets(path.join(process.cwd(), './src/public'), {
    maxAge: '1d',
    extensions: ['jpg', 'jpeg', 'png', 'gif'],
    prefix: '/static'
  })

  app.useGlobalPipes(new ValidationPipe({ transform: true }))
  app.useGlobalFilters(new HttpExceptionFilter())
  app.useGlobalInterceptors(new TransformInterceptor())

  console.log(`Nest application successfully started on ${'http://localhost:3300'}`)
  await app.listen(3300)
}

bootstrap()
